import { memo } from 'react'
import styles from './index.module.scss'
import { useTitle } from 'ahooks'
import { Typography, Space, Form, Input, Button, Checkbox, message } from 'antd'
import { UserOutlined } from '@ant-design/icons'
import { Link, useNavigate } from 'react-router-dom'
import { Rule } from 'antd/lib/form'
import { usenameRules, passwordRules } from '@/utils/constant'
import { api_login } from '@/api'
import { useRequest } from 'ahooks'

const { Title } = Typography

type loginType = {
  username: string
  password: string
  remember: boolean
}

const Login = memo(() => {
  useTitle('用户登录')
  const nav = useNavigate()

  const onFinish = async (values: loginType) => {
    if (values.remember) {
      remember(values.username, values.password)
    } else {
      localStorage.removeItem('username')
      localStorage.removeItem('password')
    }
    handleLogin(values)
  }

  const { run: handleLogin } = useRequest(
    async ({ username, password }) => await api_login({ username, password }),
    {
      manual: true,
      onSuccess: res => {
        localStorage.setItem('token', res.token)
        message.success('登录成功')
        nav('/manage/list')
      },
    }
  )

  const remember = (username: string, password: string) => {
    localStorage.setItem('username', username)
    localStorage.setItem('password', btoa(password))
  }

  return (
    <div className={styles.container}>
      <div>
        <Space>
          <Title level={2}>
            <UserOutlined />
          </Title>
          <Title level={2}>用户登录</Title>
        </Space>
      </div>
      <div>
        <Form
          onFinish={onFinish}
          validateTrigger="onBlur"
          initialValues={{
            username: localStorage.getItem('username') || '',
            password: atob(localStorage.getItem('password') || ''),
            remember: false,
          }}
          style={{ minWidth: 300 }}
        >
          <Form.Item name="username" rules={usenameRules as Rule[]}>
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item name="password" rules={passwordRules as Rule[]}>
            <Input.Password placeholder="请输入密码" />
          </Form.Item>

          <Form.Item name="remember" valuePropName="checked" style={{ margin: 0 }}>
            <Checkbox checked>记住我</Checkbox>
          </Form.Item>

          <Form.Item style={{ textAlign: 'center' }}>
            <Space direction="vertical" style={{ textAlign: 'center', width: '100%' }}>
              <Button type="primary" htmlType="submit" block>
                登录
              </Button>
              <Link to="/register">没有账户，立即注册</Link>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
})

export default Login
